<?php

namespace app\admin\model\inventory;

use app\admin\model\outhouse\Kcmx;
use think\Db;
use think\Log;
use think\Model;
use traits\model\SoftDelete;

class Kc extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'kc';
    
    // 自动写入时间戳字段
   // protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    /**
     * 调拨单处理数据
     * @return void
     */
    public static function tbdjUpdataKc($data, $warehouseCode)
    {
        //减去原货架库存，再添加一条新的货架库存
        self::where(['id' => $data['kc_id']])->setDec('iQuantity', $data['tp_iQuantity']);
        //原货架减库存做日志
        Kcmx::commonKcmxParams($data['code'],$data['code_date'],$data['tp_iQuantity'],$data['cInvCode'],'',$data['shelves_id'],$data['warehouse_id'],4);

        $id = self::where([
            'shelves_id' => $data['shelves_change_id'],
            'warehouse_id' => $data['warehouse_change_id'],
            'cInvCode' => $data['cInvCode'],
        ])->order('iQuantity asc')->value('id');
        if ($id) {
            self::where(['id' => $data['kc_id']])->setInc('iQuantity', $data['tp_iQuantity']);
        } else {
            $insertData = [
                'cWhCode' => $warehouseCode,
                'cInvCode' => $data['cInvCode'],
                'iQuantity' => $data['tp_iQuantity'],
                'createtime' => date('Y-m-d H:i:s', time()),
                'shelves_id' => $data['shelves_change_id']
            ];
            self::insert($insertData);
        }
        //新货架添加日志
        Kcmx::commonKcmxParams($data['code'],$data['code_date'],$data['tp_iQuantity'],$data['cInvCode'],'',$data['shelves_change_id'],$data['warehouse_change_id'],4);
    }

    /**
     * 采购更新库存
     * @param $data
     * @return void
     * @throws \think\Exception
     */
     public static function produreUpdateKc($data){
         $cInvCode           = $data ['cInvCode'];
         $iQuantity          = $data ['iQuantity'];
         $where['cInvCode']  = $cInvCode;

         if(empty($data['shelves_id'])){
             $shelvesId = Db::name('inventory')->where(['number'=>$cInvCode])->value('shelves_id');
             if($shelvesId){
                 $where['shelves_id']= $shelvesId;
             }
         }else{
             $where['shelves_id'] = $data['shelves_id'];
             $shelvesId           = $data['shelves_id'];
         }
         $id = self::where($where)->order('iQuantity asc')->value('id');
         if(!$id){
             //如果找不到对应库存记录，则新增一条
             //本来应该是调u8库存记录，没有则再那边新增后，同步过pc这边再操作
             $id = Db::name('kc')->insertGetId([
                 'AutoID' => '',
                 'warehouse_id' => $data['warehouse_id'],
                 'cWhCode' => $data['cWhCode'],
                 'cInvCode' => $data['cInvCode'],
                 'iQuantity' => $data['iQuantity'],
                 'shelves_id' => $data['shelves_id'],
                 'createtime' => date('Y-m-d H:i:s')
             ]);
         }else{
             self::where( ['id'=>$id])->setInc('iQuantity',$iQuantity);
         }
         
         Kcmx::commonKcmxParams($data['code'],$data['code_date'], $iQuantity, $cInvCode, '', $shelvesId,$data['warehouse_id'], 1);
         

     }
    /**
     * 领料单减少库存
     * @param $data
     * @return void
     */
    public static function materialUpdateKc($data){
        //建议货架扣，如果建议货架没，则找条有记录的，扣掉那个货架的库存

        $cInvCode          = $data ['cInvCode'];
        $iQuantity         = $data ['iQuantity'];
        $where['cInvCode'] = $cInvCode;
         
        if(empty($data['shelves_id'])){
            //读取物料，默认默认
             $shelvesId = Db::name('inventory')->where(['number'=>$cInvCode])->value('shelves_id');
             if($shelvesId){
                 $where['shelves_id']= $shelvesId;
             }
        }else{
             $where['shelves_id'] = $data['shelves_id'];
             $shelvesId           = $data['shelves_id'];
        }
         
        $id = self::where($where)->order('iQuantity desc')->value('id');

        if($id){
             self::where( ['id'=>$id])->setDec('iQuantity',$iQuantity);
        }else{
             Log::error('找不到库存'.var_export($data,true));
        }
         //添加明细 领料出库
        Kcmx::commonKcmxParams($data['code'],$data['code_date'],$iQuantity,$cInvCode,'',$shelvesId,$data['warehouse_id'],2);
    }

    /**
     * 其他入库出库库存操作
     * @param $warehouseCode
     * @param $shelvesId
     * @param $cInvCode
     * @param $iQuantity
     * @param $code
     * @param $code_date
     * @param $operation_type 1：增加库存，2:减少库存
     * @param $mx_type  5：其他入库，6：其他出库  、7上架出库 、8上架入库 9采购退回 10领料退回
     * @return void
     * @throws \think\Exception
     */
    public static function rdRecordUpdateKc($warehouseCode,$warehouse_id,$shelvesId,$createtime, $cInvCode, $iQuantity, $code, $code_date, $operation_type, $mx_type,$remark='')
    {
        //建议货架扣，如果建议货架没，则找条有记录的，扣掉那个货架的库存
        //$shelvesId = Db::name('inventory')->where(['number' => $cInvCode])->value('shelves_id');
        
        $where['cWhCode'] =$warehouseCode;
        $where['cInvCode'] =$cInvCode;
        if($shelvesId){
            $where['shelves_id']= $shelvesId;
        }
        $id = self::where($where)->order('iQuantity desc')->value('id');
        if(!$id&&$operation_type == 2&&$mx_type==8){
            //调拨
            $id = intval($remark);
        }
        
        if(!$id&&$operation_type == 2){
            exception('减库存-找不到库存记录');
        }
        if(!$id&&$operation_type == 1){
            //新增库存，但无库存记录的，新增1条0库存的
            self::addData([
                'AutoID' => 0,
                'cWhCode' => $warehouseCode,
                'warehouse_id' => $warehouse_id,
                'cInvCode' => $cInvCode,
                'iQuantity'=>0,
                'createtime'=>date('Y-m-d H:i:s',time()),
                'shelves_id'=>$shelvesId
            ]);
        }
        
        self::updateDataKc($warehouseCode,$warehouse_id,$shelvesId, $cInvCode, $iQuantity, $operation_type,$id);
        //添加明细
        Kcmx::commonKcmxParams($code, $code_date, $iQuantity, $cInvCode, '', $shelvesId,$warehouse_id, $mx_type,$remark);
    }

    /**
     * 统一修改库存
     * @param $shelvesId
     * @param $cInvCode
     * @param $iQuantity
     * @param $type
     * @return void
     * @throws \think\Exception
     */
    public static function  updateDataKc($warehouseCode,$warehouse_id,$shelvesId,$cInvCode, $iQuantity,$type = 1,$kc_id = 0){
        $where['cWhCode'] =$warehouseCode;
        $where['cInvCode'] =$cInvCode;
        if($shelvesId){
            $where['shelves_id']= $shelvesId;
        }
        
        //$id = self::where($where)->order('iQuantity desc')->value('id');
        if($kc_id){
            $kc = self::get($kc_id);
        }else{
            $kc = self::where($where)->order('iQuantity desc')->find();
        }
        
        if($kc){
            //增加库存
            if($type ==  1){
                $re  = self::where( ['id'=>$kc['id']])->setInc('iQuantity',$iQuantity);
            }else{
                //判断库存是否满足
                if($kc->iQuantity<$iQuantity){
                    exception("物料[{$kc->cInvCode}]库存不足");
                }
                //减少库存
                self::where( ['id'=>$kc['id']])->setDec('iQuantity',$iQuantity);
            }
            //更新仓库id
            if(!$kc['warehouse_id']){
                self::where( ['id'=>$kc['id']])->update([
                    'warehouse_id' => $warehouse_id
                ]);
            }
        }else{
            Log::error('物料编码'.$cInvCode.'找不到库存');
            exception('物料编码'.$cInvCode.'找不到库存');
        }
    }
    
    /*
     * //第一种类似调拨（表体b_reamrk记录的是库存id）
     * 上架操作（原库存记录无货架上架、直接上架）
     * 先减无货架库存记录，再新增1条库存记录（不能直接更改货架id，有可能要分多个货架放）
     * param $v pda单据表体提交上来的记录
     *   */
    public static function shangjiaUpdateDataKc($code,$code_date,$warehouseCode,$warehouse_id,$v){
        $check_kc_id = intval($v['b_remark']);
        if($check_kc_id){
            $kc = self::get($check_kc_id);
            if(!$kc){
                exception("物料[{$v['inv_number']}],找不到库存记录[{$check_kc_id}]");
            }
            if(!empty($kc->shelves_id)){
                exception("物料 [{$v['inv_number']}],库存记录[{$check_kc_id}],已上架,请核实");
            }
            //先减原库存记录
            self::updateDataKc('','','','', $v['fqty'],2,$check_kc_id);
            //添加明细
            Kcmx::commonKcmxParams($code,$code_date,$v['fqty'],$v['inv_number'],'',0,$warehouse_id,10,'库存记录无货架，直接操作上架，减库存');
            
            //再加新库存
            $createtime = date('Y-m-d H:i:s');
            self::rdRecordUpdateKc($warehouseCode,$warehouse_id,$v['shelves_id'],$createtime, $v['inv_number'], $v['fqty'], $code, $code_date, 1, 10,'库存记录无货架，直接操作上架，加库存');
        }else{
            //直接上架，直接加库存
            self::rdRecordUpdateKc($warehouseCode,$warehouse_id,$v['shelves_id'],$createtime, $v['inv_number'], $v['fqty'], $code, $code_date, 1, 10,'直接操作上架，加库存');
        }
    }
    
    public static function addData($data){

        $data = [
            'AutoID' => $data['AutoID'],
            'cWhCode' => $data['cWhCode'],
            'warehouse_id' => $data['warehouse_id'],
            'cInvCode' => $data['cInvCode'],
            'iQuantity'=>$data['iQuantity'],
            'createtime'=>date('Y-m-d H:i:s',time()),
            'shelves_id'=>$data['shelves_id']
        ];
        self::insert($data);
    }
    
    //获取即时库存 没货架id返回所有
    public static function getKcQty($warehouse_id,$shelvesId = 0,$cInvCode){
        if(!$warehouse_id||!$cInvCode){
            return ;
        }
        $warehouse_number = db('warehouse')->where('id',$warehouse_id)->value('number');
        if(!$warehouse_number){
            exception("仓库ID{$warehouse_id}异常");
        }
        
        $qty = 0;
        $where = [
            'cWhCode' => $warehouse_number,
            'cInvCode' => $cInvCode
        ];
        
        if($shelvesId){
            $where['shelves_id'] = $shelvesId;
            $qty = self::where($where)->value('iQuantity');
        }else{
            $qty = self::where($where)->sum('iQuantity');
        }
        
        $digits = 4;
        $qty_format_arr = config('site.float_data_formatter');
        if(isset($qty_format_arr['digits'])){
            $digits = $qty_format_arr['digits'];
        }
        return round($qty,$digits);        
    }
    
    
    //获取即时库存 直接读u8
    public static function getU8KcQty($warehouse_id,$cInvCode){
        if(!$warehouse_id||!$cInvCode){
            return ;
        }
        
        $warehouse_number = db('warehouse')->where('id',$warehouse_id)->value('number');
        if(!$warehouse_number){
            exception("仓库ID{$warehouse_id}异常");
        }
        
        $iQuantity = Db::connect('database.sec')->table('CurrentStock')
        ->where([
            'cWhCode' => $warehouse_number,
            'cInvCode' => $cInvCode
        ])
        ->sum('iQuantity');
        //->value('iQuantity',0);
        
        return round($iQuantity ,4);
    }
    
    //获取即时库存 直接读u8
    public static function getU8KcCodes($warehouse_id = 0){
        $where = [
            'iQuantity' => ['GT',0]
        ];
        if($warehouse_id){
            $warehouse_number = db('warehouse')->where('id',$warehouse_id)->value('number');
            if(!$warehouse_number){
                exception("仓库ID{$warehouse_id}异常");
            }
            $where['cWhCode'] = $warehouse_number;
        }
        
        $cInvCodeArr = Db::connect('database.sec')->table('CurrentStock')
        ->where($where)
        ->distinct('cInvCode')
        ->column('cInvCode');
        if($cInvCodeArr){
            $cInvCodeArr = array_keys($cInvCodeArr);
        }
        return $cInvCodeArr;
    }
    
    /*
     * 获取物料推荐仓库、货架，不用这个，直接在物料里面读，新增了2个字段 warehouse_name shelves_name
     *   */
    public static function getTjWhShID($inv_number,$warehouse_code = ''){
        $where = [
            'cInvCode' => $inv_number
        ];
        if ($warehouse_code){
            $where['cWhCode'] = $warehouse_code;
        }
        $where['shelves_id'] = ['neq','not null']; //不为空
        $kc = self::where($where)->field('id,shelves_id,warehouse_id')->find();
        if(!$kc){
            $kc = [
                'id' => '',
                'warehouse_id' => '',
                'shelves_id' => ''
            ];
        }
        return $kc;
    }
}
